/**
 * Copyright (C) 2010 altuure <altuure [AT] gmail [DOT] com> http://www.altuure.com/projects/yagdao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.altuure.yagdao.base;

import static org.junit.Assert.assertEquals;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.altuure.yagdao.YLimit;
import com.altuure.yagdao.YPage;
import com.altuure.yagdao.dao.OrderDAO;
import com.altuure.yagdao.dao.OrderItemDAO;
import com.altuure.yagdao.dao.ProductDAO;
import com.altuure.yagdao.dao.SimpleBeanDAO;
import com.altuure.yagdao.model.Customer;
import com.altuure.yagdao.model.Order;
import com.altuure.yagdao.model.OrderItem;
import com.altuure.yagdao.model.Product;
import com.altuure.yagdao.model.SimpleBean;

public abstract class DAOTestHelper {

    protected OrderDAO orderDAO;
    protected OrderItemDAO orderItemDAO;
    protected ProductDAO productDAO;
    protected SimpleBeanDAO simpleBeanDAO;
    private boolean initDone = false;

    public DAOTestHelper() {
        super();

    }

    public final void init() throws Exception {
        if (!initDone) {
            initDB();

            populateDB();
            initDAO();
            checkDAOs();

        }
        initDone = true;
    }

    public abstract Object get(Class clz, Long id);

    private void checkDAOs() {
        if (orderDAO == null)
            throw new NullPointerException(" orderDAO is null");
        if (orderItemDAO == null)
            throw new NullPointerException(" orderItemDAO is null");
        if (productDAO == null)
            throw new NullPointerException(" productDAO is null");
        if (simpleBeanDAO == null)
            throw new NullPointerException(" simpleBeanDAO is null");

    }

    private void populateDB() {
        initCustomers();
        initProducts();
        initSimpleBeans();

        initOrders();

    }

    protected abstract void initDAO() throws Exception;

    protected abstract void initDB() throws Exception;

    protected abstract void beginTx();

    protected abstract void commitTx();

    protected abstract void rollbackTx();

    public abstract void save(Object object);

    public Object executeQuery(String queryString, Object... args) {
        return executePageQuery(queryString, null, args);
    }

    public abstract Object executeNamedQuery(String queryName, YLimit page, Object... args);

    public abstract Object executeNamedQuery(String queryName, YLimit page, Map<String, Object> args);

    public abstract Object executePageQuery(String queryString, YLimit page, Object... args);

    public abstract Object executePageQuery(String queryString, YLimit page, Map<String, Object> args);

    public abstract Object executeSingleQuery(String queryName, Object... args);

    public abstract Object executeSingleQuery(String queryName, Map<String, Object> args);

    public void assertEqualsList(List actual, List expected) {
        assertEquals(expected, actual);
    }

    public void assertEqualsList(List actual, String query, YPage page, Object... args) {
        assertEquals(executePageQuery(query, page, args), actual);
    }

    private void initProducts() {
        beginTx();
        save(new Product("table", 200, 100.0d));
        save(new Product("lux phone", 201, 270.0d));
        save(new Product("chair", 300, 120.0d));
        save(new Product("lux chair", 301, 120.0d));
        save(new Product("bookshelf", 400, 170.0d));
        save(new Product("lamb", 500, 100.0d));
        save(new Product("pen", 600, 120.0d));
        save(new Product("mobile phone", 700, 170.0d));

        commitTx();

    }

    private void initCustomers() {
        beginTx();
        for (int i = 0; i < 10; i++) {
            save(new Customer("company-" + i, "city-" + i));
        }

        commitTx();

    }

    private void initOrders() {
        beginTx();
        List<Product> products = (List<Product>) executeQuery("from Product t");
        List<Customer> customers = (List<Customer>) executeQuery("from Customer t");
        for (int i = 0; i < 40; i++) {
            initOrder(products, customers);

        }

        commitTx();

    }

    private void initOrder(List<Product> products, List<Customer> customers) {
        int code = (int) Math.ceil(Math.random() * 10000d);
        int itemCount = (int) Math.ceil(Math.random() * 10d);
        Order order = new Order();
        order.deliveryDate = new Date();
        order.orderDate = new Date();
        order.name = "ORDER-" + code;
        order.priority = (int) Math.ceil(Math.random() * 10d);
        double totalValue = 0;
        for (int i = 0; i < itemCount; i++) {
            Product p = products.get((int) Math.floor(products.size() * Math.random()));
            OrderItem item = new OrderItem();
            item.product = p;
            item.name = p.name;
            item.quantity = (int) Math.ceil(Math.random() * 10000d);
            item.totalPrice = item.quantity * p.price;
            totalValue += item.totalPrice;
            order.items.add(item);

        }

        order.customer = customers.get((int) Math.floor(customers.size() * Math.random()));

        order.totalValue = totalValue;
        save(order);
        for (OrderItem item : order.items) {
            item.order = order;
            save(item);
        }
    }

    private void initSimpleBeans() {
        beginTx();
        for (int i = 0; i < 1000; i++) {
            save(SimpleBean.randomBean());

        }

        commitTx();
    }

}
